/***
 * 切换表格头弹窗
 */
import React, {
  useState,
  useCallback,
  useRef,
  useImperativeHandle,
  Ref,
} from 'react';
import { Table } from 'antd';
import { IChangeColumns, IChangeModalRef } from '../type';
import BuildTitle from '@/components/BuildTitle';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import update from 'immutability-helper';
import { MenuOutlined } from '@ant-design/icons';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import _ from 'lodash';
import { OneModal } from '@/components/one-ui';
import MyIcon from '@/components/MyIcon';

const type = 'DraggableBodyRow';

const DraggableBodyRow = ({
  index,
  moveRow,
  className,
  style,
  ...restProps
}: any) => {
  const ref = useRef<any>();
  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: type,
    collect: (monitor: any) => {
      const { index: dragIndex } = monitor.getItem() || {};
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        dropClassName:
          dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
      };
    },
    drop: (item: any) => {
      moveRow(item.index, index);
    },
  });
  const [, drag] = useDrag({
    type,
    item: { index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });
  drop(drag(ref));

  return (
    <tr
      ref={ref}
      className={`${className}${isOver ? dropClassName : ''}`}
      style={{ cursor: 'move', ...style }}
      {...restProps}
    />
  );
};

const columns = [
  {
    title: '列名',
    dataIndex: 'title',
    key: 'title',
  },
  // {
  //   title: 'dataIndex',
  //   dataIndex: 'dataIndex',
  //   key: 'dataIndex',
  // },
  {
    title: '拖动调整顺序',
    dataIndex: 'option',
    key: 'option',
    render: (text: any, record: Record<string, any> | any) => {
      return (
        <>
          {record?.unDrag ? <MyIcon type="icon-pushpin" /> : <MenuOutlined />}
        </>
      );
    },
  },
];

const resetData = (column: any[]) => {
  let selectKeys: any[] = [];
  column?.forEach((item) => {
    if (item?.visible) {
      selectKeys.push(item?.key ?? item?.dataIndex);
    }
  });
  return {
    selectKeys,
  };
};

const ChangeColumns = React.forwardRef(
  ({ onClose, columnsList, onOk }: IChangeColumns, ref) => {
    const className = 'class' + parseInt(String(Math.random() * 1000000));
    const title = <BuildTitle title={'设置显示列'} className={className} />;

    const oneModalRef: Ref<IChangeModalRef> = useRef(null); //弹框的ref

    // ref 逻辑处理
    useImperativeHandle(ref, () => ({
      onModalCancel: () => {
        if (oneModalRef) {
          if (oneModalRef.current) {
            if (oneModalRef.current.onModalCancel) {
              oneModalRef.current.onModalCancel();
            }
          }
        }
      },
    }));

    const [data, setData] = useState<any>(columnsList);
    const [selectKeys, setSelect] = useState<any>(
      resetData(columnsList).selectKeys,
    );

    const onModalOk = () => {
      onOk(data);
      // onClose();
    };

    const components = {
      body: {
        row: DraggableBodyRow,
      },
    };

    const moveRow: any = useCallback(
      (dragIndex: any, hoverIndex: any) => {
        const dragRow = data[dragIndex]; //拖拽
        const quiltRow = data[hoverIndex]; //被移动
        if (!dragRow?.unDrag && !quiltRow?.unDrag) {
          //固定列不可调整位置
          setData(
            update(data, {
              $splice: [
                [dragIndex, 1],
                [hoverIndex, 0, dragRow],
              ],
            }),
          );
        }
      },
      [data],
    );

    const onSelectChange = (key: any[], record: any[]) => {
      let newSelect = _.cloneDeep(key);
      let newColumns = data?.map((item: any) => {
        if (newSelect?.includes(item?.key || item?.dataIndex)) {
          return {
            ...item,
            visible: true,
          };
        } else {
          return {
            ...item,
            visible: false,
          };
        }
      });
      setData(newColumns);
      setSelect(newSelect);
    };

    return (
      <OneModal
        open={true}
        onCancel={onClose}
        centered={true}
        className={className}
        title={title}
        onOk={onModalOk}
        bodyStyle={{ padding: 0, height: window.screen.height * 0.4 }}
        width={window.screen.width * 0.4}
        ref={oneModalRef}
      >
        <ScrollBarLayout
          style={{
            padding: '1rem',
          }}
        >
          <DndProvider backend={HTML5Backend}>
            <Table
              columns={columns}
              dataSource={data}
              size={'small'}
              pagination={false}
              components={components}
              bordered
              onRow={(record: any, index: any) =>
              ({
                index,
                moveRow,
              } as any)
              }
              rowKey={(record) => record?.key ?? record?.dataIndex}
              rowSelection={{
                type: 'checkbox',
                onChange: onSelectChange,
                columnTitle: (
                  <span style={{ whiteSpace: "nowrap" }}>
                    显示
                  </span>
                ),
                selectedRowKeys: selectKeys,
                getCheckboxProps: (record) => {
                  return {
                    disabled: record?.unDrag,
                  };
                },
              }}
            />
          </DndProvider>
        </ScrollBarLayout>
      </OneModal>
    );
  },
);

export default ChangeColumns;
